package top.pmwly.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.pmwly.common.domain.UserSecurity;
import top.pmwly.common.domain.vo.MenuVo;
import top.pmwly.common.utils.TreeUtils;
import top.pmwly.common.constant.ReslutEnum;
import top.pmwly.common.reslut.ReslutBean;
import top.pmwly.dao.mapper.SysMenuMapper;
import top.pmwly.dao.pojo.SysMenu;
import top.pmwly.service.ISysMenuService;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author Herther
 * @since 2021-09-21
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {


    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public ReslutBean getMenuById() {
        //从SpringSecurity上下文对象获取 用户主体
        UserSecurity sysUser = (UserSecurity)
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //去redis查找菜单
        ValueOperations opsForValue = redisTemplate.opsForValue();
        List<MenuVo> redisMenus = (List<MenuVo>) opsForValue.get("/menu?param id= " + sysUser.getSysUser().getUserId());
        //如果不为空则放回
        if (!CollectionUtils.isEmpty(redisMenus)){
            return ReslutBean.SUCCESS(ReslutEnum.SUCCESS,redisMenus);
        }
        //redis不存在menus则去查询
        //执行查询
        List<SysMenu> menus =  sysMenuMapper.selectMenuById(sysUser.getSysUser().getUserId());
        if (null == menus){
            return ReslutBean.FAIL(ReslutEnum.FAIL_AUTHORITY);
        }
        //构建树
        TreeUtils treeUtils = new TreeUtils(menus);
        List<MenuVo> menuVos = treeUtils.builderTree();
        //将菜单数据放入redis中
        opsForValue.set("/menu?param id= "+sysUser.getSysUser().getUserId(), menuVos);
        //返回
        return ReslutBean.SUCCESS(ReslutEnum.SUCCESS,menuVos);
    }
}
